const app = getApp();
var util = require('../../../utils/util.js');

Page({
    data: {
        userInfo: null,
        balance: 0,
        bankCards: [],
        selectedCard: null,
        amount: '',
        minWithdraw: 100, // 最小提现金额
        maxWithdraw: 0,   // 最大提现金额（将根据用户余额设置）
        withdrawFee: 0,   // 提现手续费
        actualAmount: 0,   // 实际到账金额
        feeRate: 0.006,    // 手续费率（0.6%）
        showConfirmModal: false
    },

    onLoad: function() {
        wx.setNavigationBarTitle({
            title: '提现'
        });
    },

    onShow: function() {
        // 获取用户信息和余额
        this.getUserInfo();
        // 获取用户银行卡列表
        this.getBankCards();
		this.getTixianPro();
    },

    // 获取用户信息和余额
    getUserInfo: function() {
        const that = this;
        util.httpRrquest(app.data.rooturl + 'weixin/getUserInfo', 'GET', {})
            .then(function(response) {
                if (response.data.code === 1) {
                    const userData = response.data.data;
                    that.setData({
                        userInfo: userData,
                        balance: userData.userBalance || 0,
                        maxWithdraw: userData.userBalance || 0
                    });
                } else {
                    wx.showToast({
                        title: response.data.msg || '获取用户信息失败',
                        icon: 'none'
                    });
                }
            }, function(error) {
                console.log(error);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
    },

    // 获取用户银行卡列表
    getBankCards: function() {
        const that = this;
        util.httpRrquest(app.data.rooturl + 'user/getBankcard', 'GET', {})
            .then(function(response) {
                if (response.data.code === 1) {
                    const cards = response.data.data || [];
                    // 查找默认银行卡
                    const defaultCard = cards.find(card => card.isDefault === 1);
                    that.setData({
                        bankCards: cards,
                        selectedCard: defaultCard || (cards.length > 0 ? cards[0] : null)
                    });
                } else {
                    wx.showToast({
                        title: response.data.msg || '获取银行卡列表失败',
                        icon: 'none'
                    });
                }
            }, function(error) {
                console.log(error);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
    },

    // 选择银行卡
    selectCard: function(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({
            selectedCard: this.data.bankCards[index]
        });
    },
	getTixianPro:function(){
		const that = this;
        util.httpRrquest(app.data.rooturl + 'user/getTixianPro', 'GET', {})
            .then(function(response) {
                if (response.data.code === 1) {
                    that.setData({
                        feeRate: response.data.data||0
                    });
                }
            }, function(error) {
                console.log(error);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
	},
    // 添加银行卡
    addBankCard: function() {
        wx.navigateTo({
            url: '/pages/mine/bankcard/add/add'
        });
    },
    // 输入提现金额
    inputAmount: function(e) {
        const amount = e.detail.value;
        let withdrawFee = 0;
        let actualAmount = 0;
        
        if (amount && !isNaN(amount)) {
            withdrawFee = parseFloat((amount * this.data.feeRate).toFixed(2));
            actualAmount = parseFloat((amount - withdrawFee).toFixed(2));
        }
        
        this.setData({
            amount: amount,
            withdrawFee: withdrawFee,
            actualAmount: actualAmount
        });
    },

    // 全部提现
    withdrawAll: function() {
        const balance = this.data.balance;
        let withdrawFee = parseFloat((balance * this.data.feeRate).toFixed(2));
        let actualAmount = parseFloat((balance - withdrawFee).toFixed(2));
        
        this.setData({
            amount: balance.toString(),
            withdrawFee: withdrawFee,
            actualAmount: actualAmount
        });
    },

    // 显示确认提现弹窗
    showConfirmWithdraw: function() {
        // 表单验证
        if (!this.data.selectedCard) {
            wx.showToast({
                title: '请选择或添加银行卡',
                icon: 'none'
            });
            return;
        }
        
        const amount = parseFloat(this.data.amount);
        if (!amount || isNaN(amount)) {
            wx.showToast({
                title: '请输入有效的提现金额',
                icon: 'none'
            });
            return;
        }
        
        if (amount < this.data.minWithdraw) {
            wx.showToast({
                title: `提现金额不能低于${this.data.minWithdraw}元`,
                icon: 'none'
            });
            return;
        }
        
        if (amount > this.data.balance) {
            wx.showToast({
                title: '提现金额不能大于可用余额',
                icon: 'none'
            });
            return;
        }
        
        this.setData({
            showConfirmModal: true
        });
    },

    // 取消提现
    cancelWithdraw: function() {
        this.setData({
            showConfirmModal: false
        });
    },

    // 确认提现
    confirmWithdraw: function() {
        const that = this;
        const amount = parseFloat(this.data.amount);
        
        wx.showLoading({
            title: '提交中...',
        });
        
        util.httpRrquest(app.data.rooturl + 'user/addTixian', 'POST', {
            cardId: that.data.selectedCard.id,
            amount: amount,
            fee: that.data.withdrawFee,
            actualAmount: that.data.actualAmount
        })
            .then(function(response) {
                wx.hideLoading();
                that.setData({
                    showConfirmModal: false
                });
                
                if (response.data.code === 1) {
                    wx.showModal({
                        title: '提现申请已提交',
                        content: '您的提现申请已成功提交，我们将在1-3个工作日内处理，请留意到账情况。',
                        showCancel: false,
                        success: function() {
                            // 刷新用户余额
                            that.getUserInfo();
                            // 清空提现金额
                            that.setData({
                                amount: '',
                                withdrawFee: 0,
                                actualAmount: 0
                            });
                        }
                    });
                } else {
                    wx.showToast({
                        title: response.data.msg || '提现申请失败',
                        icon: 'none'
                    });
                }
            }, function(error) {
                wx.hideLoading();
                console.log(error);
                wx.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
    }
})